package com.manor.common;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.danikula.videocache.HttpProxyCacheServer;
import com.ishumei.smantifraud.SmAntiFraud;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.L;
import com.mob.adsdk.AdConfig;
import com.mob.adsdk.AdSdk;
import com.mob.gamesdk.GameConfig;
import com.mob.gamesdk.GameSdk;
import com.mob.videosdk.VideoConfig;
import com.mob.videosdk.VideoSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.multidex.BuildConfig;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;
import me.jessyan.autosize.AutoSize;
import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.onAdaptListener;
import me.jessyan.autosize.utils.AutoSizeLog;


/**
 * Created by cxf on 2017/8/3.
 */

public class CommonAppContext extends MultiDexApplication {

    public static CommonAppContext sInstance;
    private int mCount;
    private boolean mFront;//是否前台
    private HttpProxyCacheServer proxy;
    /**
     * 数美publicKey
     */
    private static final String SM_PUBLIC_KEY = "/++/i/+//+s//+////";
    /**
     * 数美infoKey
     */
    public static final String SM_INFO_KEY = "";
    /**
     * 数美Organization
     */
    public static final String SM_ORGANIZATION = "";
    /**
     * 数美appID
     */
    public static final String SM_APPID = "taomi";


    public static HttpProxyCacheServer getProxy(Context context) {
        CommonAppContext app = (CommonAppContext) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer(this);
    }


    @GlideModule
    public final class MGlideModule extends AppGlideModule {
        //        @Override
        //        public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        //            int bitmapPoolSizeBytes = 1024 * 1024 * 0; // 0mb
        //            int memoryCacheSizeBytes = 1024 * 1024 * 0; // 0mb
        //            builder.setMemoryCache(new LruResourceCache(memoryCacheSizeBytes));
        //            builder.setBitmapPool(new LruBitmapPool(bitmapPoolSizeBytes));
        //        }

        @Override
        public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
            super.registerComponents(context, glide, registry);
        }

        @Override
        public boolean isManifestParsingEnabled() {
            return false;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        //初始化Http
        CommonHttpUtil.init();
        Utils.init(this);

        registerActivityLifecycleCallbacks();

        //屏幕适配
        AutoSize.initCompatMultiProcess(this);
        AutoSizeConfig.getInstance()
                .setExcludeFontScale(true)
                //屏幕适配监听器
                .setOnAdaptListener(new onAdaptListener() {
                    @Override
                    public void onAdaptBefore(Object target, Activity activity) {
                        AutoSizeLog.d(String.format(Locale.ENGLISH, "%s onAdaptBefore!", target.getClass().getName()));
                    }

                    @Override
                    public void onAdaptAfter(Object target, Activity activity) {
                        AutoSizeLog.d(String.format(Locale.ENGLISH, "%s onAdaptAfter!", target.getClass().getName()));
                    }
                })
                .setLog(BuildConfig.DEBUG);

        //保活先干掉，耗电
        // initKeep();

        FaceSDKManager.getInstance().initialize(this, "TaoMi-face-android", "idl-license.face-android");
        initBDFace();

        //初始化友盟统计
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null);
        MobclickAgent.setCatchUncaughtExceptions(false);


        AdSdk.getInstance().init(getApplicationContext(),
                new AdConfig.Builder()
                        .appId("ae838ccf127d6b2f94")//正式的
//                        .appId("ba0063bfbc1a5ad878")//测试的
                        .multiProcess(false)
                        .debug(BuildConfig.DEBUG)
                        .build(),
                new AdSdk.InitListener() {
                    @Override
                    public void onSuccess() {
                        KLog.i("AdSdk#init----onSuccess");
                    }

                    @Override
                    public void onFailure() {
                        KLog.i("AdSdk#init----onFailure");
                    }
                });

        GameSdk.getInstance()
                .init(getApplicationContext(),
                        new GameConfig.Builder()
                                .appId("ae838ccf127d6b2f94")
                                .debug(BuildConfig.DEBUG)
                                .build(),
                        new GameSdk.InitListener() {
                            @Override
                            public void onSuccess() {
                                KLog.i("GameSdk#init----onSuccess");
                            }

                            @Override
                            public void onFailure() {
                                KLog.i("GameSdk#init----onFailure");
                            }
                        });


        VideoSdk.getInstance()
                .init(getApplicationContext(),
                new VideoConfig.Builder()
                        .appId("ae838ccf127d6b2f94")
                        .debug(BuildConfig.DEBUG)
                        .build(),
                null);


        // 初始化数美SDK
        initShuMei();
    }

    private void initShuMei() {
        if (this.getPackageName().equals(getCurProcessName(this))) {
            SmAntiFraud.SmOption option = new SmAntiFraud.SmOption();
            //1.通用配置项
            option.setOrganization(SM_ORGANIZATION);
            // 必填，组织标识，邮件中 organization 项
            option.setAppId(SM_APPID);
            // 必填，应用标识，登录数美后台应用管理查看
            option.setPublicKey(SM_PUBLIC_KEY);
            // 必填，加密 KEY，邮件中 android_public_key 附件内容
            option.setAinfoKey(SM_INFO_KEY);
            SmAntiFraud.create(this, option);
            // 4.获取设备标识，注意获取 deviceId，这个接口在需要使用 deviceId 时地方调用
            //String deviceId = SmAntiFraud.getDeviceId();
        }
    }


    public boolean isApkInDebug() {
        try {
            ApplicationInfo info = sInstance.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    protected void attachBaseContext(Context base) {
        MultiDex.install(this);
        super.attachBaseContext(base);
    }


    public void initBDFace() {
        FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();
        // SDK初始化已经设置完默认参数（推荐参数），您也根据实际需求进行数值调整
        //动作随机
        config.setLivenessRandom(true);
        //动作
        config.setLivenessTypeList(config.getLivenessTypeList());
        //模糊度（0-1）推荐小于0.7
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        //光照范围（0-1）推荐大于40
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        //裁剪人脸大小
        config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE);
        //人脸 yaw，pitch，row 角度，范围（-45，45），推荐-15-15
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        //最小检测人脸（在图片人脸能够被检测到最小值）80-200，越小越耗性能，推荐120-200
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        //
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        //人脸遮挡范围（0-1） 推荐小于0.5
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        //是否进行质量检测
        config.setCheckFaceQuality(true);
        //人脸检测使用线程数
        config.setFaceDecodeNumberOfThreads(2);

        config.setLivenessRandomCount(FaceEnvironment.VALUE_LIVENESS_DEFAULT_RANDOM_COUNT);


        FaceSDKManager.getInstance().setFaceConfig(config);
    }


    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mCount++;
                if (!mFront) {
                    mFront = true;
                    L.e("AppContext------->处于前台");
                    CommonAppConfig.getInstance().setFrontGround(true);
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                mCount--;
                if (mCount == 0) {
                    mFront = false;
                    L.e("AppContext------->处于后台");
                    CommonAppConfig.getInstance().setFrontGround(false);
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }
}
